package cn.gson.crm.controller.finance;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.DistributionDao;
import cn.gson.crm.model.dao.DistributionShadowDao;
import cn.gson.crm.model.dao.EmpDao;
import cn.gson.crm.model.dao.FollowUpDao;
import cn.gson.crm.model.dao.GradeDao;
import cn.gson.crm.model.dao.ImagesDao;
import cn.gson.crm.model.dao.SignDao;
import cn.gson.crm.model.dao.StudentDao;
import cn.gson.crm.model.dao.TransferDao;
import cn.gson.crm.model.dao.UserDao;
import cn.gson.crm.model.entity.Distribution;
import cn.gson.crm.model.entity.DistributionShadow;
import cn.gson.crm.model.entity.Emp;
import cn.gson.crm.model.entity.FollowUp;
import cn.gson.crm.model.entity.Grade;
import cn.gson.crm.model.entity.Images;
import cn.gson.crm.model.entity.Sign;
import cn.gson.crm.model.entity.Student;
import cn.gson.crm.model.entity.Transfer;
import cn.gson.crm.model.entity.User;
import cn.gson.crm.model.mapper.StudentMapper;
import lombok.extern.log4j.Log4j;

/**
 * 招生模块控制器
 * @author Jkelove
 *
 */
@Controller
@RequestMapping("/student")
@Log4j
public class StudentController {
	
	/**
	 * 学生
	 */
	@Autowired
	private StudentMapper studentMapper;
	
	/**
	 * 学生dao
	 */
	@Autowired
	private StudentDao stuDao;
	/**
	 * 用户dao
	 */
	@Autowired
	private UserDao userDao;
	
	/**
	 * 学生关注等级
	 */
	@Autowired
	private GradeDao gradeDao;
	
	/**
	 * 员工dao
	 */
	@Autowired
	private EmpDao empDao;
	
	/**
	 * 学员分配Dao
	 */
	@Autowired
	private DistributionDao disDao;
	
	@Autowired
	private DistributionShadowDao dissdDao;
	/**
	 * 跟进学员
	 */
	@Autowired
	private FollowUpDao followDao;
	
	/**
	 * 移交学员
	 */
	@Autowired
	private TransferDao transferDao;
	
	/**
	 * 图片表
	 */
	@Autowired
	private ImagesDao imgDao ;
	
	/**
	 * 签约记录
	 */
	@Autowired
	private SignDao signDao ;
	/**
	 * 查询学生
	 * @param student
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public Map<String,Object> index(Student student,@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<Student> pageData = studentMapper.studentlist(student);
		PageInfo<Student> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	/**
	 * 查询当前登录用户分配的学生
	 * @param student
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/mylist")
	@ResponseBody
	public Map<String,Object> mylist(String name,@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize,HttpServletRequest request){
		// 查询数据
		HttpSession session = request.getSession();
		User u = (User) session.getAttribute("user");
		PageHelper.startPage(pageNum, pageSize);
		List<Student> pageData = studentMapper.mystudentlist(true,"潜在",name,u.getEmp().getId());
		
		PageInfo<Student> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	/**
	 * 编辑学生
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({"/addstudent","/addstudent/{id}"})
	public String addstudent(@PathVariable(name = "id", required = false)Long id, Model model) {
		if(id != null){
			Student student = stuDao.findOne(id);
				//如果是编辑，则将原有学生信息传回表单页面
				if(student!=null) {
					model.addAttribute("student", student);
				}
		}
		return "/student/addstudent";
	}
	/**
	 * 添加学生
	 * @param student
	 * @param br
	 * @return
	 */
	@PostMapping("/save")
	@ResponseBody
	@Transactional
	public Map<String,Object> save(@Valid Student student,BindingResult br){
		Map<String,Object> obj = new HashMap<String, Object>();
		//设置日期格式
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		Grade g = new Grade();
		obj.put("success", false);
		if(br.hasErrors()) {
			obj.put("message", "保存失败！");
			obj.put("erros", br.getFieldErrors());
		}else {
			if(student.getId() == null) {
				int count=studentMapper.countStudent(student.getName());
				if (count>=1) {
					student.setName(student.getName()+count);
				}
			}
			student.setDelete(true);
			student.setState("潜在");
			//如果来源是他人推荐这关注等级为最高级
			if(student.getSource().getId()==3) {
				 g=gradeDao.findOne(1L);
			}else {
				 g=gradeDao.findOne(3L);
			}
			// new Date()为获取当前系统时间
			String today = df.format(new Date());
			student.setEntryTime(today);
			student.setGrade(g);
			stuDao.save(student);
			obj.put("success", true);
		}
		return obj;
	}
	/**
	 * 删除学员
	 * @param id
	 * @return
	 */
	@GetMapping("/delete/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> delete(@PathVariable("id") Long id){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		Student s;
		if(id != null && (s = stuDao.findOne(id)) !=null ) {
			s.setDelete(false);
			stuDao.save(s);
			obj.put("success", true);
		}else {
			obj.put("message", "此学生不存在");
		}
		return obj;
	}
	/**
	 * 指定分配学员
	 */
	@RequestMapping({"/distribution","/distribution/{id}"})
	public String distribution(@PathVariable(name = "id",required = false)Long id,Model model){
		if(id != null) {
			Student stu = stuDao.findOne(id);
			Iterable<Emp> emp = studentMapper.emplist();
			if(stu != null) {
				model.addAttribute("stu", stu);
				model.addAttribute("emp", emp);
			}
		}
		return "/student/distribution";
	}

	/**
	 * 保存分配学员
	 */
	@PostMapping("/savedistribution")
	@ResponseBody
	@Transactional
	public Map<String,Object>  savedistribution(@Valid Distribution dis,BindingResult br){
		Map<String,Object> obj = new HashMap<String, Object>();
		List<Emp> emp =studentMapper.emplist();
		//获取分配影子表里的id和姓名没有就添加
		for(int s=0;s<emp.size();s++) {
			DistributionShadow d = new DistributionShadow();
			int count = studentMapper.disshadow(emp.get(s).getId(),emp.get(s).getName());
			if(count == 0) {
				d.setName(emp.get(s).getName());
				d.setNameId(emp.get(s).getId());
				d.setDelete(true);
				d.setType(d.getType().SJ);
				dissdDao.save(d);
			}
	}
	
		obj.put("success", false);
		if(br.hasErrors()) {
			obj.put("message", "保存失败");
			obj.put("error", br.getFieldError());
		}else{
			Long id=dis.getStudents().getId();
			if(id != null) {
				Student stu=stuDao.findOne(id);
				if(stu != null) {
					stu.setEmp(dis.getEmp());
					stuDao.save(stu);
					dis.setType(dis.getType().ZD);
					dis.setDelete(true);
					disDao.save(dis);
					obj.put("success", true);
					
					DistributionShadow ds = new DistributionShadow();
					Long sid  = dis.getStudents().getId();
					String sname = dis.getStudents().getName();
					Long eid = dis.getEmp().getId();
					String ename = dis.getEmp().getName();
					DistributionShadow parent = studentMapper.disshasave(eid,ename);
					//保存分配信息到影子表
					ds.setName(sname);
					ds.setNameId(sid);
					ds.setParent(parent);
					ds.setType(ds.getType().ZD);
					dissdDao.save(ds);
					
				}
			}
		}
		return obj;
	}
	/**
	 * 待分配咨询师的学员返回到界面
	 * @param model
	 * @return
	 */
	@RequestMapping("/random")
	public void random(Model model) {
		List<Student> stu=studentMapper.studentdistribution();
		List<Emp> emp =studentMapper.emplist();
		model.addAttribute("stu", stu);
		model.addAttribute("emp", emp);
	}
	/**
	 * 返回分配记录
	 * @param dis
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/dislist")
	@ResponseBody
	public  Map<String,Object> dislist(@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		List<Student> total=studentMapper.studentdistribution();
		PageHelper.startPage(pageNum, pageSize);
		List<Student> students=studentMapper.studentdistribution();
		List<Emp> emp =studentMapper.emplist();
		List<Distribution> diss = new ArrayList<Distribution>();
		List<Distribution> d = (List<Distribution>) disDao.findAll();
		int tag = 0;
		Long id=d.get(d.size()-1).getEmp().getId();
		for(int e = 0; e<emp.size();e++) {
			if(emp.get(e).getId() == id) {
				if(e == emp.size()-1) {
					tag=-1;
				}else {
				tag = e;
				}
			}
		}
		int i = 0;
		int j = tag+1;
		
		for(i=0; i<students.size(); i++) {
			Distribution dis = new Distribution();
			dis.setStudents(students.get(i));
			dis.setEmp(emp.get(j));
			j++;
			if(j==emp.size()){
				j=0;
			}
			dis.setDelete(true);
			diss.add(i,dis);
		}
		
		PageInfo<Distribution> info = new PageInfo<>(diss);
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total",total.size());
		obj.put("rows", info.getList());
		return obj;
	}
	/**
	 * 保存分配记录
	 */
	@GetMapping("/dissave")
	@ResponseBody
	@Transactional
	public Map<String,Object> dissave() {
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		List<Student> students=studentMapper.studentdistribution();
		List<Distribution> diss = new ArrayList<Distribution>();
		List<Emp> emp =studentMapper.emplist();
		
		
		//保证公平分配每次从当前分配的咨询师下一个开始
		List<Distribution> d = (List<Distribution>) disDao.findAll();
		int tag = 0;
		Long id=d.get(d.size()-1).getEmp().getId();
		for(int e = 0; e<emp.size();e++) {
			if(emp.get(e).getId() == id) {
				if(e == emp.size()-1) {
					tag=-1;
				}else {
				tag = e;
				}
			}
		}
		int i = 0;
		int j = tag+1;
		for(i=0; i<students.size(); i++) {
			Distribution dis = new Distribution();
			dis.setType(dis.getType().SJ);
			dis.setStudents(students.get(i));
			dis.setEmp(emp.get(j));
			Student stu = stuDao.findOne(students.get(i).getId());
			stu.setEmp(emp.get(j));
			dis.setDelete(true);
			disDao.save(dis);
			stuDao.save(stu);
			j++;
			if(j==emp.size()){
				j=0;
			}
			diss.add(i, dis);
		}
		fp(students,emp,diss);
		obj.put("success", true);
		return obj;
	}
	/**
	 * 
	 * @param stu
	 * @param emp
	 * @param diss 
	 */
	private void fp(List<Student> stu,List<Emp> emp, List<Distribution> diss) {
		List<DistributionShadow>  dis = dissdDao.findAllByParentIsNullOrderByIdDesc();
		//获取分配影子表里的id和姓名没有就添加
			for(int s=0;s<emp.size();s++) {
				DistributionShadow d = new DistributionShadow();
				int count = studentMapper.disshadow(emp.get(s).getId(),emp.get(s).getName());
				if(count == 0) {
					d.setName(emp.get(s).getName());
					d.setNameId(emp.get(s).getId());
					d.setDelete(true);
					d.setType(d.getType().SJ);
					dissdDao.save(d);
				}
		}
			for(int i = 0;i<diss.size();i++) {
				DistributionShadow ds = new DistributionShadow();
				Long id = diss.get(i).getStudents().getId();
				String name = diss.get(i).getStudents().getName();
				Long eid = diss.get(i).getEmp().getId();
				String ename = diss.get(i).getEmp().getName();
				DistributionShadow parent = studentMapper.disshasave(eid,ename);
				//保存分配信息到影子表
				ds.setName(name);
				ds.setNameId(id);
				ds.setParent(parent);
				ds.setType(ds.getType().SJ);
				dissdDao.save(ds);
			}
	}
	/**
	 * 打开跟进界面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({"/follow_up","/follow_up/{id}"})
	public String follow_up(Student stu,@PathVariable(name = "id",required = false)Long id,Model model) {
		if(id != null) {
			stu = stuDao.findOne(id);
			
			if(stu != null) {
				model.addAttribute("stu", stu);
			}
		}
		Iterable<Grade> grder = gradeDao.findAll();
		model.addAttribute("g", grder);
		return "/student/follow_up";
	}
	/**
	 * 保存跟进记录
	 * @param follow
	 * @param br
	 * @return
	 */
	@PostMapping("/follow_upsave")
	@ResponseBody
	@Transactional
	public Map<String, Object> follow_upsave(@Valid FollowUp follow,BindingResult br,HttpServletRequest request) {
		Map<String,Object> obj = new HashMap<String, Object>();
		Student stu = new Student();
		obj.put("success", false);
		if(br.hasErrors()) {
			obj.put("message", "保存失败");
			obj.put("error", br.getFieldError());
		}else{
			HttpSession session = request.getSession();
			User u = (User) session.getAttribute("user");
			Emp emp = empDao.findOne(u.getEmp().getId());
			stu = stuDao.findOne(follow.getStudent().getId());
			stu.setGrade(follow.getGrade());
			follow.setEmp(emp);
			follow.setDelete(true);
			followDao.save(follow);
			stuDao.save(stu);
			obj.put("success", true);
			}
		return obj;

	}
	/**
	 * 打开移交界面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({"/transfer","/transfer/{id}"})
	public String transfer(@PathVariable(name = "id",required = false)Long id,Model model) {
		if(id != null) {
			Student stu = stuDao.findOne(id);
			
			if(stu != null) {
				model.addAttribute("stu", stu);
				
			}
		}
		List<Emp> emp =studentMapper.emplist();
		model.addAttribute("emp", emp);
		
		return "/student/transfer";
	}
	/**
	 * 保存移交界面
	 * @param transfer
	 * @param br
	 * @return
	 */
	@PostMapping("/transfersave")
	@ResponseBody
	@Transactional
	public  Map<String, Object> tranfersave(@Valid Transfer transfer,BindingResult br){
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if(br.hasErrors()) {
			obj.put("message", "保存失败");
			obj.put("error", br.getFieldError());
		}else{
			if(transfer.getAfterEmp()==transfer.getFrontEmp()) {
				obj.put("message", "不能移交给自己哦！请移交给他人！");
			}else {
				int count=studentMapper.transfercount(transfer.getStudent().getId());
				if(count>=1) {
					obj.put("message", "该学生已被移交了哦！");
				}else {
					transfer.setState("移交中");
					transferDao.save(transfer);
					Student stu = stuDao.findOne(transfer.getStudent().getId());
					stuDao.save(stu);
					obj.put("success", true);
				}
				
			}
		}
		return obj;
	}
	/**
	 * 打开签约界面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({"/sign","/sign/{id}"})
	public String sign(@PathVariable(name = "id",required = false)Long id,Model model) {
		if(id != null) {
			Student stu = stuDao.findOne(id);
			if(stu != null) {
				model.addAttribute("stu", stu);
			}
		}
		
		List<Emp> emp =studentMapper.emplist();
		model.addAttribute("emp", emp);
		
		return "/student/sign";
	}
	
	@Value("${upload.file}")
	private String uploadDir;
	
	/**
	 * 签约凭证上传
	 * @param file
	 * @return
	 */
	@PostMapping("/upload")
	@ResponseBody
	@Transactional
	public Map<String, Object> upload(
			@RequestParam("id") Long id,
			@RequestParam(defaultValue="public") String type,
			@RequestParam("file") MultipartFile file,
			HttpServletRequest request){
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		log.info(uploadDir);
		log.info("***********************学生"+id);
		try {
			//设置路径
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
			String dateDir = sdf.format(new Date());
			//获取学生信息
			Student stu = stuDao.findOne(id);
			List<Transfer> transfer=transferDao.findByStudentId(stu.getId());
			obj.put("error", null);
			String error="";
			for(Transfer t:transfer){
				if(t.getState().equals("移交中")) {
					error="该学生正在移交中，暂时不能签约！";
					obj.put("error", error);
					obj.put("success", false);
					return obj;
				}
			}
			//获取文件后缀名
			String ext = FilenameUtils.getExtension(file.getOriginalFilename());
			String newFileName = UUID.randomUUID().toString()+"."+ext;
			String filePath = String .format("%s/%s/%s", uploadDir,type,dateDir);
			File fileDir = new File(filePath);
			if(!fileDir.exists()){
				// 如果目录不存在，则创建出来
				fileDir.mkdirs();
			}
			Images img = new Images();
			img.setDelete(true);
			img.setImageType(file.getContentType());
			img.setModeType(type);
			img.setName(file.getOriginalFilename());
			img.setPath(String.format("%s/%s/%s", type,dateDir,newFileName));
			img.setSize(file.getSize());
			img.setSuffix(ext);
			img.setUploaddate(new Date());
			//将图片路径保存到数据库
			imgDao.save(img);
			
			//获取操作人信息
			HttpSession session = request.getSession();
			User u = (User) session.getAttribute("user");
			Emp emp = empDao.findOne(u.getEmp().getId());
			Images image = imgDao.findByPath(img.getPath());
			Sign s = new Sign();
			s.setEmp(emp);
			s.setStudent(stu);
			s.setDelete(true);
			s.setImage(image);
			signDao.save(s);
			stu.setState("签约");
			stuDao.save(stu);
			file.transferTo(new File(fileDir,newFileName));
			obj.put("success", true);
		} catch (IllegalStateException | IOException e) {
			log.info("文件上传失败",e);
		}
		return obj;
	}
	
	/**
	 * 获取所有分配记录
	 */
	@RequestMapping("/distributionlist")
	@ResponseBody
	public Map<String,Object> list(@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		//查询所有没有父id的分配记录
		
		
		List<DistributionShadow>  dis = dissdDao.findAllByParentIsNullOrderByIdDesc();
		for(int i = 0;i<dis.size();i++) {
			List<DistributionShadow> ds=dis.get(i).getChildren();
			Long fid = 0L;
			for(int j = 0;j<ds.size();j++) {
				Long fids = ds.get(j).getParent().getId();
				if(fid != fids) {
					List<DistributionShadow> distr = studentMapper.dissdparent(fids);
					dis.get(i).setChildren(distr);
					fid=fids;
				}
			}
		}
		obj.put("total", dis.size());
		obj.put("rows", dis);
		return obj;
	}
	/**
	 * 学生详情
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping({"/student_details/{id}"})
	public String studentDetails(@PathVariable(name = "id",required = false)Long id,Model model) {
		if(id != null) {
			Student stu = stuDao.findOne(id);
			if(stu != null) {
				model.addAttribute("studetail", stu);
			}
			if(!stu.getBirthdays().equals("")||!stu.getBirthdays().isEmpty()) {
				Date newTime = new Date();
				int year = newTime.getYear()+1900 ;
				String birthday=stu.getBirthdays().substring(0, 4);
				int a=Integer.parseInt(birthday);
				int age=year-a;
				model.addAttribute("age", age);
			}
				
		}
		
		return "/student/student_details";
	}
	
	/**
	 * 移交列表
	 * @param transfer
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/transferList")
	@ResponseBody
	public Map<String,Object> transferList(Transfer transfer,@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<Transfer> pageData = studentMapper.transferList(transfer);
		PageInfo<Transfer> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	/**
	 * 打开我的消息窗口
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping("transfer_massage")
	public String transferMassage(HttpServletRequest request,Model model) {
		HttpSession session = request.getSession();
		User u = (User) session.getAttribute("user");
		int transfer = studentMapper.massageCount(u.getEmp().getId(), "进行中");
		model.addAttribute("t", transfer);
		return "student/transfer_massage";
	}
	/**
	 * 我的消息列表
	 * @param request
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/mymassagelist")
	@ResponseBody
	public Map<String,Object> mymassagelist(HttpServletRequest request,@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		PageHelper.startPage(pageNum, pageSize);
		HttpSession session = request.getSession();
		User u = (User) session.getAttribute("user");
		List<Transfer> pageData = studentMapper.massageList(u.getEmp().getId(), "进行中");
		PageInfo<Transfer> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	/**
	 * 拒绝移交
	 * @param transfer
	 * @param id
	 * @return
	 */
	@GetMapping("/deletemessage/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> deletemessage(@Valid Transfer transfer,@PathVariable("id") Long id){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if(id != null && (transfer = transferDao.findOne(id)) !=null ) {
			transfer.setState("已拒绝");
			transferDao.save(transfer);
			Emp e = empDao.findOne(transfer.getFrontEmp().getId());
			Student stu = stuDao.findOne(transfer.getStudent().getId());
			stu.setEmp(e);
			stuDao.save(stu);
			obj.put("success", true);
		}else {
			obj.put("message", "此学生不存在");
		}
		return obj;
	}
	/**
	 * 同意移交
	 * @param transfer
	 * @param id
	 * @return
	 */
	@GetMapping("/agreemessage/{id}")
	@ResponseBody
	@Transactional
	public Map<String,Object> agreemessage(@Valid Transfer transfer,@PathVariable("id") Long id){
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("success", false);
		if(id != null && (transfer = transferDao.findOne(id)) !=null ) {
			transfer.setState("已同意");
			transferDao.save(transfer);
			Emp e = empDao.findOne(transfer.getAfterEmp().getId());
			Student stu = stuDao.findOne(transfer.getStudent().getId());
			stu.setEmp(e);
			stuDao.save(stu);
			obj.put("success", true);
		}else {
			obj.put("message", "此学生不存在");
		}
		return obj;
	}
	
	/**
	 * 签约列表
	 * @param sign
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@RequestMapping("/signList")
	@ResponseBody
	public Map<String,Object> signList(Sign sign,@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize){
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<Sign> pageData = studentMapper.signList(sign);
		PageInfo<Sign> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String,Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
	
	@GetMapping({"sign_student_details/{id}"})
	public String signDetails(@PathVariable(name = "id", required = false) Long id, Model model) {
		System.out.println("id"+id);
		if (id != null) {
			Sign s =signDao.findOne(id);
			if (s != null) {
				// 如果是编辑，则把原有用户信息传回表单页面
				model.addAttribute("stu", s);
			}
			if(!s.getStudent().getBirthdays().equals("")||!s.getStudent().getBirthdays().isEmpty()) {
				Date newTime = new Date();
				int year = newTime.getYear()+1900 ;
				String birthday=s.getStudent().getBirthdays().substring(0, 4);
				int a=Integer.parseInt(birthday);
				int age=year-a;
				model.addAttribute("age", age);
			}
		}
		return "student/sign_student_details";
	}
	
	
	/**
	 * 预览
	 */
	@GetMapping("/ylimg/**")
	@ResponseBody
	public void preview(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String path = request.getServletPath();
		log.info(path);
		path = path.replaceFirst("/student/ylimg/", uploadDir);
		ServletOutputStream os = response.getOutputStream();
		File f = new File(path);
		log.info(f);
		if (!f.exists()) {
			// 附件不存在的时候，直接返回404
			response.sendError(404);
			return;
		}
		// 创建一个输入流
		FileInputStream fis = new FileInputStream(f);
		// 每次读取的字节数
		byte[] b = new byte[2048];
		// 每次实际读取到的字节长度
		int len = 0;
		while ((len = fis.read(b)) > 0) {
			// 进入循环，表示读取到了字节
			// 读到多少，就写出多少
			os.write(b, 0, len);
		}

		fis.close();
	}
	
	/**
	 * 咨询师业绩统计图
	 * @param sign
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/emptjtList")
	@ResponseBody
	public Map<String,Object> emptjtList(Sign sign,HttpServletRequest request,HttpServletResponse response){
		// 组装返回结果
		Map<String,Object> map = new HashMap<String, Object>();
		// 查询数据
		List<Sign> pageData = studentMapper.emptjtList(sign);
		log.info("pageData:"+pageData);
		if(null!=pageData && pageData.size()>0) {
			map.put("emptjt", pageData);
		}  
		return map;
	}
}
